import 'package:enjoy_plus_hm/utils/eventbus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';

import '../../utils/http.dart';
import '../../utils/toast.dart';

class MinePage extends StatefulWidget {
  MinePage({super.key, required this.currentIndex});
  int currentIndex;
  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  // 菜单数据
  final List menuList = [
    {"title": "我的房屋", "icon": "assets/images/house_profile_icon@2x.png"},
    {"title": "我的报修", "icon": "assets/images/repair_profile_icon@2x.png"},
    {"title": "访客记录", "icon": "assets/images/visitor_profile_icon@2x.png"},
  ];
  Map userInfo = {"id": "", "avatar": null, "nickName": null};
  void getUserInfo() async {
    try {
      final res = await http.get('/userInfo');
      if (res['code'] != 10000) return ToastUtil.showError('请求失败');
      ToastUtil.showSuccess('请求成功');
      setState(() {
        userInfo = res['data'];
      });
    } catch (e) {
      ToastUtil.showError('请求失败');
    }
  }

  @override
  void initState() {
    super.initState();
    eventBus.on<refreshMineEvent>().listen((event) {
      getUserInfo();
    });
    eventBus.on<profileToMineEvent>().listen((event) {
      getUserInfo();
    });
  }

  @override
  void didUpdateWidget(covariant MinePage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.currentIndex == 1) {
      // 调用接口,刷新页面
      getUserInfo();
    }
  }

  @override
  Widget build(BuildContext context) {
    return (Scaffold(
      backgroundColor: const Color.fromARGB(255, 133, 179, 199),
      //Scaffold 是 Flutter 实现 Material Design 页面布局的核心组件，提供标准化 UI 框架，包含顶栏（appBar）、
      //主体内容（body）、抽屉菜单（drawer）、悬浮按钮（floatingActionButton）等模块。
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.transparent,
        title: Text('我的', style: TextStyle(color: Colors.white, fontSize: 16)),
      ),
      body: ListView(
        children: [
          Container(
            margin: EdgeInsets.all(20),

            child: GestureDetector(
              onTap: () {
                Navigator.pushNamed(context, '/profile');
              },

              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          userInfo['avatar'] == null
                              ? Image.asset(
                                'assets/images/avatar_1.jpg',
                                width: 32,
                                height: 32,
                              )
                              : Image.network(
                                userInfo['avatar'],
                                width: 32,
                                height: 32,
                              ),

                          SizedBox(width: 10),
                          Text(
                            '${userInfo['nickName'] ?? '暂无昵称'}',
                            style: TextStyle(fontSize: 14, color: Colors.white),
                          ),
                        ],
                      ),

                      TextButton(
                        onPressed: () {
                          Navigator.pushNamed(
                            context,
                            '/profile',
                            arguments: userInfo,
                          );
                        },
                        child: Text(
                          '去完善信息 >',
                          style: TextStyle(fontSize: 14, color: Colors.white),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.all(20),
            padding: EdgeInsets.all(10),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              color: Colors.white,
            ),
            child: Column(
              children:
                  menuList.map((item) {
                    return GestureDetector(
                      onTap: () {},
                      child: Container(
                        padding: EdgeInsets.only(top: 10, bottom: 10),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Image.asset(item['icon'], width: 15),
                                SizedBox(width: 10),
                                Text(
                                  item['title'],
                                  style: TextStyle(fontSize: 12),
                                ),
                              ],
                            ),
                            Text(
                              '>',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.grey,
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  }).toList(),
            ),
          ),
        ],
      ),
    ));
  }
}
